export default {
  data() {
    return {
      videoAd: null, // 激励视频广告
    };
  },
  watch: {
    "$store.state.configInfo": {
      handler() {
        this.createRewardedVideoAd();
      },
      immediate: true,
    },
  },
  methods: {
    createRewardedVideoAd() {
      if (wx.createRewardedVideoAd) {
        this.videoAd = wx.createRewardedVideoAd({
          adUnitId: this.$store.state.configInfo.adIds.rewardedVideoAd,
        });
        this.videoAd.onLoad(() => {});
        this.videoAd.onError((err) => {
          console.error("激励视频光告加载失败", err);
        });
        // this.videoAd.onClose((res) => { })
      }
    },
    // 下载图片
    async handleDownload(src) {
      const res = await uni.showModal({
        title: "提示",
        content: "服务器维护需要成本，看个广告支持一下吧~",
      });
      if (!res.confirm) return;
      this.videoAd.show().catch(() => {
        this.videoAd
          .load()
          .then(() => this.videoAd.show())
          .catch((err) => {
            uni.showToast({
              title: "广告显示失败",
              icon: "none",
            });
          });
      });

      this.videoAd.onClose((res) => {
        if (res && res.isEnded) {
          this.saveImage(src);
        } else {
          console.log("播放中途退出，不下发奖励");
        }
      });
    },
    async saveImage(src) {
      const info = await uni.getImageInfo({
        src,
      });
      uni.saveImageToPhotosAlbum({
        filePath: info.path,
        success: () => {
          uni.showToast({
            title: "保存成功",
            icon: "success",
          });
        },
        fail: (err) => {
          uni.showToast({
            title: "保存失败: " + err.errMsg,
            icon: "none",
          });
        },
      });
    },
  },
};
